package com.study.shiro.realm;

import com.study.shiro.entity.User;
import com.study.shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 陈烨庆
 * @date 2023/4/27
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 自定义授权方法
     * @param principals the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("自定义授权方法");

        // 1. 获取用户身份信息
        String principal = principals.getPrimaryPrincipal().toString();

        // 2. 调用业务层获取用户的角色信息(数据库)
        List<String> roles = userService.getUserRoleInfoByName(principal);
        System.out.println("当前用户的角色信息:" + roles);

        // 2.5. 获取用户的角色权限信息(数据库)
        List<String> permissions = userService.getUserPermissionInfoByRoles(roles);
        System.out.println("当前用户的权限信息:" + permissions);

        // 3. 创建对象,封装当前登录用户的角色, 权限信息
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        // 2. 存储角色
        info.addRoles(roles);
        info.addStringPermissions(permissions);

        // 3. 返回信息
        return info;
    }

    /**
     * 自定义登录认证方法
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 1. 获取用户身份信息
        String name = token.getPrincipal().toString();
        // 2. 调用业务层获取用户信息(数据库)
        User userInfo = userService.getUserInfoByName(name);

        // 3. 判断用户是否存在 将数据完成封装并返回
        if (userInfo != null) {
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    token.getPrincipal(),
                    userInfo.getPwd(),
                    ByteSource.Util.bytes("salt"),
                    token.getPrincipal().toString()
            );
            return info;
        }
        return null;
    }
}
